<template>

  <div>
    <el-alert
      style="background-color: #409EFF; color: #222222; font-style: unset; margin-top: 10px; margin-bottom: 20px"
      :closable="false" title="员工管理"
    />
    <el-form :inline="true" class="demo-form-inline">
      <el-button v-if="hasAuth('views.user.users.user.add')" style="margin-left: 25px" type="primary"
                 @click="dialogFormVisible = true"
      ><i class="el-icon-circle-plus-outline"></i>添加员工
      </el-button>
    </el-form>
    <el-divider></el-divider>

    <!--  编辑员工信息  -->
    <el-dialog width="85%" title="编辑员工" :visible.sync="dialogFormVisible">
      <el-form size="mini" :model="editForm" :rules="rules" ref="addForm">
        <el-row gutter="20">
          <el-col :span="6">
            <el-form-item label="头像" prop="image" :label-width="formLabelWidth">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :action="url"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="editForm.image" :src="editForm.image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="合同期限" prop="contractTerm" :label-width="formLabelWidth">
              <el-input style="width: 200px" v-model="editForm.contractTerm"
                        autocomplete="off"
              >
                <template slot="append">年</template>
              </el-input>

            </el-form-item>
            <el-form-item label="合同起始日期" prop="beginContract" :label-width="formLabelWidth">
              <el-date-picker
                style="width: 200px"
                v-model="editForm.beginContract"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="合同终止日期" prop="endContract" :label-width="formLabelWidth">
              <el-date-picker
                style="width: 200px"
                v-model="editForm.endContract"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="工龄" :label-width="formLabelWidth">
              <el-input style="width: 200px" v-model="editForm.workAge" autocomplete="off">
                <template slot="append">年</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-row>
              <el-col :span="8">
                <el-form-item label="姓名" prop="realName" :label-width="formLabelWidth">
                  <el-input style="width: 200px" :disabled="editForm.id" v-model="editForm.realName"
                            autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                  <el-input style="width: 200px" :disabled="editForm.id" v-model="editForm.username"
                            autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="出生日期" prop="age" :label-width="formLabelWidth">
                  <el-date-picker
                    style="width: 200px"
                    v-model="editForm.age"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                  />
<!--                  <el-input style="width: 200px" v-model="editForm.age" autocomplete="off"></el-input>-->
                </el-form-item>
                <el-form-item label="部门" prop="departmentId" :label-width="formLabelWidth">
                  <el-select style="width: 200px" v-model="editForm.departmentId" autocomplete="off">
                    <el-option v-for="item in departmentList" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="职称" prop="jobLevelId" :label-width="formLabelWidth">
                  <el-select style="width: 200px" v-model="editForm.jobLevelId" autocomplete="off">
                    <el-option v-for="item in jobLevelList" :label="item.name" :value="item.id"
                               :disabled="item.enabled == '0'"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="最高学历" prop="degree" :label-width="formLabelWidth">
                  <el-select style="width: 200px" v-model="editForm.degree" autocomplete="off">
                    <el-option v-for="item in degreeList" :label="item" :value="item"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="入职日期" prop="beginDate" :label-width="formLabelWidth">
                  <el-date-picker
                    style="width: 200px"
                    v-model="editForm.beginDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="转正日期" prop="conversionTime" :label-width="formLabelWidth">
                  <el-date-picker
                    style="width: 200px"
                    v-model="editForm.conversionTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>

              </el-col>
              <el-col :span="8">

                <el-form-item label="专业" :label-width="formLabelWidth">
                  <el-input style="width: 200px" v-model="editForm.specialty" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="政治面貌" prop="politicId" :label-width="formLabelWidth">
                  <el-select style="width: 200px" v-model="editForm.politicId" autocomplete="off">
                    <el-option v-for="item in politicsStatusList" :label="item.name" :value="item.name"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex" :label-width="formLabelWidth">
                  <el-select style="width: 200px" v-model="editForm.sex" autocomplete="off">
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="职位" prop="posId" :label-width="formLabelWidth">
                  <el-select style="width: 200px" v-model="editForm.posId" autocomplete="off">
                    <el-option v-for="item in positionList" :label="item.name" :value="item.id"
                               :disabled="item.enabled == '0'"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="在职状态" prop="workState" :label-width="formLabelWidth">
                  <el-select style="width: 200px" v-model="editForm.workState" autocomplete="off">
                    <el-option label="在职" value="在职"></el-option>
                    <el-option label="离职" value="离职"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="离职日期" prop="endWordDate" :label-width="formLabelWidth">
                  <el-date-picker
                    style="width: 200px"
                    v-model="editForm.endWordDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="工资账套" prop="salaryId" :label-width="formLabelWidth">
                  <el-select style="width: 200px" v-model="editForm.salaryId" autocomplete="off">
                    <el-option v-for="item in salaryList" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系方式" prop="phone" :label-width="formLabelWidth">
                  <el-input style="width: 200px"  v-model="editForm.phone"
                            autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="毕业院校" prop="school" :label-width="formLabelWidth">
                  <el-input style="width: 200px" v-model="editForm.school" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="身份证号" prop="nbr" :label-width="formLabelWidth">
                  <el-input style="width: 200px" :disabled="editForm.id" v-model="editForm.nbr"
                            autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="籍贯" :label-width="formLabelWidth">
                  <el-input style="width: 200px" type="textarea" v-model="editForm.nationPlace"
                            autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="具体住址" :label-width="formLabelWidth">
                  <el-input style="width: 200px" type="textarea" v-model="editForm.address"
                            autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="备注" :label-width="formLabelWidth">
                  <el-input style="width: 200px" type="textarea" v-model="editForm.remark"
                            autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('addForm')">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--  :cell-style="{'text-align':'center'}" 列表文字居中  -->
    <el-table id="tableData" class="content" tooltip-effect="dark" border size="small"
              :data="tableData.slice((currentPage-1)*PageSize,currentPage*PageSize)"
              :cell-style="{'text-align':'center'}"
    >
      <!--      <el-table-column prop="nbr" label="学号/工号"/>-->

      <el-table-column prop="realName" label="姓名" align="center"/>
      <!--      <el-table-column prop="nickname" label="昵称" align="center"/>-->
      <el-table-column prop="username" label="用户名" align="center"/>
      <el-table-column prop="sex" label="性别" align="center"/>
      <el-table-column prop="age" label="出生日期" align="center"/>
      <el-table-column prop="phone" label="电话" align="center"/>

      <!--   头像列   -->
      <el-table-column label="头像" align="center">
        <template slot-scope="scope">
          <el-button type="success" size="small" plain @click="mouseOver(scope.row)">预览</el-button>

        </template>
      </el-table-column>

      <!--   创建时间与最后登录时间   -->
      <el-table-column prop="createTime" label="创建时间" align="center" min-width="105px"/>
      <el-table-column prop="lastLoginTime" label="最后登录时间" align="center" min-width="105px"/>

      <!--   状态列   -->
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag type="success" size="small" plain v-if="scope.row.enable == '1'">启用</el-tag>
          <el-tag type="danger" size="small" plain v-if="scope.row.enable == '0'">禁用</el-tag>
        </template>
      </el-table-column>

      <!--   操作列   -->
      <el-table-column
        fixed="right"
        label="操作"
        v-if="hasAuth('views.user.users.user.update') "
        width="300" align="center"
      >
        <template slot-scope="scope">
          <el-button v-if="scope.row.enable == '1' && hasAuth('views.user.users.user.update')"
                     type="text" size="small"
                     @click="updateUserRootId2(scope.row)"

          >禁用
          </el-button>
          <el-button v-if="scope.row.enable == '0' && hasAuth('views.user.users.user.update')" type="text" size="small"
                     @click="updateUserRootId3(scope.row)"
          >启用
          </el-button>
          <el-divider v-if="hasAuth('views.user.users.user.update')" direction="vertical"></el-divider>
          <el-button v-if="hasAuth('views.user.users.sys.userRole.assignRole')" @click="showAssignRoleDialog(scope.row)"
                     size="small" slot="reference" type="text"
          >分配权限
          </el-button>
          <el-divider v-if="hasAuth('views.user.users.sys.userRole.assignRole')" direction="vertical"></el-divider>
          <el-button v-if="hasAuth('views.user.users.user.resetPassword')" @click="resetPassword(scope.row.id)"
                     size="small" slot="reference" type="text"
          >重置密码
          </el-button>
          <el-divider v-if="hasAuth('views.user.users.user.resetPassword')" direction="vertical"></el-divider>
          <el-button v-if="hasAuth('views.user.users.user.update')" @click="openEditForm(scope.row)" size="small"
                     slot="reference" type="text"
          >编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--  预览头像  -->
    <el-dialog title="预览" width="15%" :visible.sync="showUserImg">
      <el-image :src="imageUrl"></el-image>
    </el-dialog>


    <el-dialog ref="assignRole" title="分配权限" width="30%" :visible.sync="showAssignRoleForm"

    >
      <!--   去掉了：@selection-change="loadUserFormRole"   -->

      <el-table
        ref="multipleTable"
        :data="allRoleList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >

        <el-table-column type="selection" width="55"/>
        <!--        <el-table-column prop="id"  label="ID" width="15px"/>-->
        <el-table-column prop="name" label="权限编码" width="155px"/>
        <el-table-column prop="nameZh" label="权限名称" width="175px"/>
      </el-table>

      <!--   按钮   -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssignRoleForm()">确 定</el-button>
        <el-button @click="closeForm()">取 消</el-button>
      </div>
      <div style="margin-top: 20px">
        <el-button @click="selectHaveRoles()">查看角色信息</el-button>
      </div>
    </el-dialog>


    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      style="align-content: center; align-items: center"
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :total="totalCount"
      :page-size="PageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import { validatePhone } from '@/utils/validator'

export default {
  name: 'AllType',
  data() {
    return {
      imageUrl: '',
      showUserImg: false,
      /*
      * 基础数据
      * */
      //添加表单的数据
      tableData: [],
      // 默认显示第几页
      currentPage: 1,
      // 个数选择器（可修改）
      pageSizes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      // 总条数，根据接口获取数据长度(注意：这里不能为空)
      totalCount: 1,
      // 个数选择器（可修改）
      PageSize: 10,
      formLabelWidth: '120px',
      searchForm: {},
      allRoleList: [],
      userHaveRoles: [],
      showAssignRoleForm: false,
      assignRoleForm: {},
      multipleSelection: [],
      degreeList: ['博士', '硕士', '本科', '大专', '高中', '初中', '小学', '其他'],
      //添加表单
      url: 'http://127.0.0.1:8083/img/imgUpload', //文件上传地址
      editForm: {
        image: ''
      },
      dialogFormVisible: false,
      departmentList: [], //部门
      politicsStatusList: [], //政治面貌
      jobLevelList: [], // 职称
      positionList: [], //职位
      salaryList: [], // 工资账套
      rules: {
        image: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
        realName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        /*nickname: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],*/
        studentFlag: [{ required: true, message: '学生标志不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
        nbr: [{ required: true, message: '证件号码不能为空', trigger: 'blur' }],
        age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
        departmentId: [{ required: true, message: '学部不能为空', trigger: 'blur' }],
        politicId: [{ required: true, message: '政治面貌不能为空', trigger: 'blur' }],
        sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        jobLevelId: [{ required: true, message: '请选择职称', trigger: 'blur' }],
        degree: [{ required: true, message: '请选择最高学历', trigger: 'blur' }],
        posId: [{ required: true, message: '请选择职位', trigger: 'blur' }],
        beginDate: [{ required: true, message: '请选择入职日期', trigger: 'blur' }],
        // endWordDate: [{ required: true, message: '请选择离职日期', trigger: 'blur' }],
        workState: [{ required: true, message: '请选择在职状态', trigger: 'blur' }],
        contractTerm: [{ required: true, message: '请输入合同期限', trigger: 'blur' }],
        beginContract: [{ required: true, message: '请输入合同起始日期', trigger: 'blur' }],
        endContract: [{ required: true, message: '请输入合同终止日期', trigger: 'blur' }],
        salaryId: [{ required: true, message: '请选择工资账套', trigger: 'blur' }]
      },

      allRoleIdList: []
    }
  },

  mounted() {
    this.load()
    if (this.hasAuth('views.user.users.user.update')) {
      this.loadAllRole()
      this.loadAllDepartment() //加载部门
      this.loadPolitics() //加载政治面貌
      //加载职位
      this.loadAllPosition()
      //加载职称
      this.loadAllJobLevel()
      //加载工资账套
      this.loadAllSalary()
    }
  },

  methods: {
    openEditForm(row) {
      this.editForm = {}
      this.editForm = row
      this.dialogFormVisible = true
    },
    submitForm(editForm) {
      this.$refs[editForm].validate((valid) => {
        if (valid) {
          this.editForm.roles = []
          this.axios.post('/user/' + (this.editForm.id ? 'update' : 'add'), this.editForm).then(resp => {
            if (resp.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                onClose: () => { //关闭回调
                }
              })
              this.dialogFormVisible = false
              this.editForm = {}
              this.load()
            }
          })
        }
      })
    },
    submitAssignRoleForm() {
      let roles = []
      this.assignRoleForm.roles.forEach(role => {
        let userRole = {
          userId: this.assignRoleForm.id,
          roleId: role.id
        }
        roles.push(userRole)
      })
      this.axios.post('/sys/userRole/assignRole/' + this.assignRoleForm.id, roles).then(resp => {
        if (resp.code == 200) {
          this.$message({
            message: '操作成功',
            type: 'success',
            onClose: () => { //关闭回调
            }
          })
          this.showAssignRoleForm = false
          this.load()
        }
      })
    },

    /**
     * 1.获取Row上的ID
     * @param row
     */
    showAssignRoleDialog(row) {
      this.assignRoleForm = {}
      this.showAssignRoleForm = true
      this.assignRoleForm = JSON.parse(JSON.stringify(row))

      console.log('1.获取当前行的用户的ID（row.id）：' + row.id)
      //加载用户ID查询角色选中信息
      this.loadUserFormRole(row.id)

      //反显到复选框
      this.selectHaveRoles()
    },
    handleSelectionChange(val) {
      //********val为选中状态的集合
      this.assignRoleForm.roles = val
      console.log('this.assignRoleForm.roles=' + this.assignRoleForm.roles)
    },

    //重置密码方法
    resetPassword(id) {
      this.axios.get('/user/resetPassword/' + id).then(resp => {
        if (resp.code == 200) {
          this.$message({
            message: '操作成功',
            type: 'success',
            onClose: () => { //关闭回调
            }
          })
        }
      })
    },
    /**
     * 预览头像
     * @param row
     */
    mouseOver(row) {
      this.showUserImg = true
      this.imageUrl = ''
      this.imageUrl = row.image
    },

    /**
     * 禁用
     **/
    updateUserRootId2(row) {
      row.enable = 0
      console.log(row)
      this.axios.post('user/update', row).then((resp) => {
          this.load()
        }
      )
    },
    /**
     * 启用
     **/
    updateUserRootId3(row) {
      row.enable = 1
      console.log(row)
      this.axios.post('user/update', row).then((resp) => {
          this.load()
        }
      )
    },
    // 分页
    // 每页显示的条数
    handleSizeChange(val) {
      this.PageSize = val
      this.currentPage = 1
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    loadPolitics() {
      this.axios.post('/politicsStatus/select', {}).then((resp) => {
          this.politicsStatusList = resp.data
        }
      )
    },
    loadAllDepartment() {
      this.axios.post('/department/select', {}).then(resp => {
        this.departmentList = resp.data
      })
    },
    loadAllSalary() {
      this.axios.post('/salary/select', {}).then(resp => {
        this.salaryList = resp.data
      })
    },
    loadAllJobLevel() {
      this.axios.post('/jobLevel/select', {}).then(resp => {
        this.jobLevelList = resp.data
      })
    },
    loadAllPosition() {
      this.axios.post('/position/select', {}).then(resp => {
        this.positionList = resp.data
      })
    },
    loadAllRole() {
      this.axios.post('/sys/role/select', {}).then(resp => {
        this.allRoleList = resp.data

        resp.data.forEach(data => {

        })
      })
    },
    load() {
      this.axios.post('/user/select', this.searchForm).then(
        (resp) => {
          this.tableData = resp.data
          this.totalCount = resp.data.length
        }
      )
    },
    handleAvatarSuccess(res, file) {
      this.editForm.image = 'http://127.0.0.1:8083/' + res[0]
      // this.url = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
    },
    hasAuth(url) {
      let auth = this.$store.state.menu.authorizationList
      return auth.indexOf(url) > -1
    },

    /**
     * 2.从后端根据user_id,加载用户的角色信息
     * @param id
     */
    loadUserFormRole(id) {
      this.axios.post('/sys/role/selectRole/' + id).then(resp => {
        let userRoles = []
        resp.data.forEach(data => {
          console.log('  从后端传输过来的数据（data）：' + data)
          userRoles.push(data)
        })
        console.log('  获取当前行用户所拥有的角色信息（userRoles）' + userRoles)
        this.userHaveRoles = userRoles
      })
      console.log('2.获取当前行用户所拥有的角色信息（this.userHaveRoles=）' + this.userHaveRoles)
      this.selectHaveRoles()
    },

    /**
     * 3. 校验用户的角色ID与所有的ID进行重复的数据并计算行数
     */
    selectHaveRoles() {
      let allRoleIds = []
      var theRow = 0
      this.allRoleList.forEach(data => {
        allRoleIds.push(data.id)
      })
      console.log('3.获取所有角色的ID（this.allRoleList）：' + allRoleIds)

      console.log('4.验证当前行角色的角色信息（this.userHaveRoles）：' + this.userHaveRoles)

      //校验用户角色所拥有的权限是否存在
      if (this.userHaveRoles.length > 0) {
        //遍历用户所拥有的角色
        this.userHaveRoles.forEach(data => {
            if (allRoleIds.includes(data.roleId)) {
              console.log('allRoleIds.indexOf(data.roleId)=' + allRoleIds.indexOf(data.roleId))
              //所拥有的角色的行数1
              theRow = allRoleIds.indexOf(data.roleId)
              this.toggleSelection([this.allRoleList[theRow]])
            }
          }
        )
      }else{
        this.$message({
          message: '当前用户暂未分配角色！！！',
          type: 'error'
        })
      }
    },
    //选择第几行的数据（复选框）
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },

    closeForm() {
      this.showAssignRoleForm = false
      this.$refs.multipleTable.clearSelection()
    }
  }

}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 211px;
  height: 211px;
  line-height: 211px;
  text-align: center;
}

.avatar {
  width: 211px;
  height: 211px;
  display: block;
}

.table {
  border-radius: 5px;
  margin: 10px;
  background-color: #FAFAFA;
  /*text-align: center;*/
}

.content {
  -webkit-box-shadow: #666 0px 0px 10px;
  -moz-box-shadow: #666 0px 0px 10px;
  box-shadow: #666 0px 0px 10px;
  background: #EEFF99;

  /*margin-right: 15px;*/
  /*margin-left: 15px;*/
}

.el-table {
  border-radius: 5px;
  margin-right: 15px;
  margin-left: 15px;
  margin-bottom: 10px;
  width: 98%;
}
</style>
